//
// Created by xuchao on 16-11-24.
//

#ifndef OKPG_OKPGUTILS_H
#define OKPG_OKPGUTILS_H

#include "OkPgException.h"

namespace OKPg {
    static const std::string K_EMPTY_STR = "";
    static const int K_DEFAULT_INT = 0;
    static const std::string K_NULL_STR = "";
    static const int K_NULL_INT = -1;

    static inline int string2int(const std::string &str) {
        char *e;
        int r = strtol(str.c_str(), &e, 10);
        if (e == str) {
            throw OkPgException("Number format exception:", str);
        }
        return r;
    }

    static inline long long string2longLong(const std::string &str) {
        char *e;
        int r = strtoll(str.c_str(), &e, 10);
        if (e == str) {
            throw OkPgException("Number format exception:", str);
        }
        return r;
    }

    static inline double string2double(const std::string &str) {
        char *e;
        double r = strtod(str.c_str(), &e);
        if (e == str) {
            throw OkPgException("Number format exception:", str);
        }
        return r;
    }

    template<typename T=int>
    static inline std::string toString(const T x) {

        return std::to_string(x);
    }

    static inline std::string time2string(const time_t &t) {
        tm tt = *gmtime(&t);
        char buff[32] = {};
        strftime(buff, 32, "%Y-%m-%d %H:%M:%S", &tt);
        return buff;
    }

    static inline int checkColumnIndex(int columnIndex, int columnCount) {
        int i = columnIndex - 1;
        if (columnCount <= 0 || i < 0 || i >= columnCount)
            throw new OkPgException(
                    "Column index exception:Column index %d is out of range!", columnCount);
        return i;
    }

    static inline int checkParamIndex(int paramIndex, int paramCount) {
        int i = paramIndex - 1;
        if (paramCount <= 0 || i < 0 || i >= paramCount)
            throw new OkPgException(
                    "Param index exception:Param index %d is out of range!", paramIndex);
        return i;
    }

}

#endif //OKPG_OKPGUTILS_H
